/**
 * JAVACC DEMO 1.0
 * @copy right apache company All rights reserved. 
 * @Package com.apache.task.controller  
 */
package com.apache.portal.task;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apache.api.vo.ResultEntity;
import com.apache.database.model.Page;
import com.apache.database.model.TaskEntity;
import com.apache.portal.common.PortalPlugin;
import com.apache.portal.common.annotion.BeanFactory;
import com.apache.portal.common.util.PortalPubFactory;
import net.sf.json.JSONObject;

import com.apache.api.vo.ResultMsg;
import com.apache.portal.common.restfull.RequestMapping;
import com.apache.portal.common.restfull.ResultFullAnntation;
import com.apache.portal.common.restfull.SupperAction;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;

/**
 * description:  定时任务管理Action
 * @author Hou Dayu 创建时间：2016-1-21
 * @Copyright(c)2014:
 */
@SuppressWarnings("serial")
@ResultFullAnntation(name = "timeTaskAction", urlPatterns = { "/task/*" })
public class TimeTaskAction extends SupperAction {

	private PortalPlugin plugin;
	private String isFile;

	public void init() {
		plugin = (PortalPlugin) BeanFactory.getInstance().getBeans("info");
		isFile = StrUtil.doNull(ToolsUtil.getInstance().getLocalByKey("config.properties","read.file.database"),"file");
	}

	protected void doInvoke(HttpServletRequest request, HttpServletResponse response, String methodType)
			throws Exception {
		Method method = doInvoke(this.getClass(), request, response, methodType, "");
		if (null != method) {
			Object obj = method.invoke(this, request, response);
			if (!ToolsUtil.isEmpty(obj)) {
				JSONObject array = JSONObject.fromObject(obj);
				this.outputJson(array.toString(), response, request.getParameter("callback"));
			}
		} else {
			gotoErrorPage(request, response, "请求方式有误或请求地址未定义");
		}
	}

	@RequestMapping(value = "list!data.action")
	public Object data(HttpServletRequest request, HttpServletResponse response)throws IOException {
		// String page = request.getp, String rows
		Map<String, Object> mapData = new HashMap<String, Object>();
        mapData.put("total","0");
        mapData.put("source", isFile);
		if("file".equals(isFile)){
			List<TaskEntity> list = ScheduledExecutor.newInstance().getTasks();
			mapData.put("total", list.size());
			mapData.put("rows", list);
		}else{
            ///sysName不能为空
            Map<String, String> params = this.getParameterMap(request);
            params.put("doCode", "listTaskTimer");
            ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response, params);
            if(entity.getEntity()==null){
                return mapData;
            }
            if(entity.getEntity() instanceof Page){
                Page page = (Page)entity.getEntity();
                mapData.put("total", page.getCount());
                mapData.put("rows", page.getPageObjects());
            }else{
                List list = (List)entity.getEntity();
                mapData.put("total", list.size());
                mapData.put("rows", list);
            }
		}
		return mapData;
	}

	/**
	 * description:  添加线程跳转页面
	 */
	@RequestMapping(value = "add.action")
	public TaskEntity add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String key = request.getParameter("key");
		TaskEntity task = new TaskEntity();
		if (StrUtil.isNotNull(key)) {
            if("file".equals(isFile)){
                List<TaskEntity> list = ScheduledExecutor.newInstance().getTasks();
                for (TaskEntity te : list) {
                    if (key.equals(te.getTaskKey())) {
                        task = te;
                        break;
                    }
                }
            }else{
                Map<String, String> params = this.getParameterMap(request);
                params.put("doCode", "infoTaskTimer");
                if(StrUtil.isNull(params.get("serverIp"))) {
                    String serverIp = PortalPubFactory.getLocalIp();
                    params.put("serverIp", serverIp);
                }
                params.put("taskKey", request.getParameter("key"));
                ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,params);
                if(null != entity.getEntity()){
                    task = (TaskEntity)entity.getEntity();
                }
            }
		}
		return task;
		//		view.addObject("item", task);
		//		return view;
	}

	/**
	 * description:  添加线程
	 */
	@RequestMapping(value = "save.action", method = "post")
	public ResultMsg save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        if("file".equals(isFile)){
            TaskEntity item = new TaskEntity();
            item.setClassName(request.getParameter("className"));
            item.setDescription(request.getParameter("description"));
            item.setEndTime(Integer.valueOf(StrUtil.doNull(request.getParameter("endTime"), "0")));
            item.setStartTime(Integer.valueOf(StrUtil.doNull(request.getParameter("startTime"), "0")));
            item.setHour(Long.valueOf(StrUtil.doNull(request.getParameter("hour"), "1")));
            item.setIntervalType(Long.valueOf(StrUtil.doNull(request.getParameter("intervalType"), "0")));
            item.setMinute(Long.valueOf(StrUtil.doNull(request.getParameter("minute"), "0")));
            item.setSecond(Long.valueOf(StrUtil.doNull(request.getParameter("second"), "0")));
            item.setTaskKey(StrUtil.doNull(request.getParameter("taskKey"), ""));
            String isAdd = "false";
            if (StrUtil.isNull(item.getTaskKey())) {
                isAdd = "true";
            }
            String id = "";
            boolean mark = false;
            if (item.getIntervalType() == 1) {//如果选择按每天定时执行,小时项未填写则默认此项为1
                if (item.getHour() <= 1) {
                    item.setHour(1l);
                }
            }
            if ("false".equals(isAdd) && item != null) {
                List<TaskEntity> list = ScheduledExecutor.newInstance().getTasks();
                int i = 0;
                for (TaskEntity te : list) {
                    if (item.getTaskKey().equals(te.getTaskKey())) {
                        if (te.isOpenStart()) {
                            rmsg.setFlag("F");
                            rmsg.setMsg("任务已开启不能修改");
                            return rmsg;
                        }
                        list.remove(te);
                        break;
                    }
                    i++;
                }
                //ScheduledExecutor.newInstance().setTask(item);
                list.add(i, item);
                mark = XmlReader.newInstance().writeXml(list);
            } else {
                List<TaskEntity> list = ScheduledExecutor.newInstance().getTasks();
                id = XmlReader.newInstance().noZero(list.size() + "", 3, "1");
                item.setTaskKey(id);
                list.add(item);
                mark = XmlReader.newInstance().writeXml(list);
                if (item.getTaskStatus() == 1) {
                    ScheduledExecutor.newInstance().start(id);
                }
            }
            if (("false".equals(isAdd) && !mark) || ("true".equals(isAdd) && StrUtil.isNull(id))) {
                rmsg.setFlag("F");
                rmsg.setMsg("操作失败！");
            }
        }else{
            ///sysName不能为空
            Map<String, String> params = this.getParameterMap(request);
            if(StrUtil.isNull(params.get("serverIp"))) {
                String serverIp = PortalPubFactory.getLocalIp();
                params.put("serverIp", serverIp);
            }
            params.put("doCode", "saveTaskTimer");
            ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response, params);
            if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
                rmsg = new ResultMsg("T", String.valueOf(entity.getEntity()));
            } else {
                rmsg = new ResultMsg("F", entity.getMessage());
            }
        }
		return rmsg;
	}

	@RequestMapping(value = "del.action")
	public ResultMsg delTask(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String key = request.getParameter("key");
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");
		if (StrUtil.isNotNull(key)) {//开启所有线程
            if("file".equals(isFile)){
                List<TaskEntity> list = ScheduledExecutor.newInstance().getTasks();
                for (TaskEntity te : list) {
                    if (key.equals(te.getTaskKey())) {
                        if (te.isOpenStart()) {
                            rmsg.setFlag("F");
                            rmsg.setMsg("任务已开启不能删除");
                            return rmsg;
                        }
                        list.remove(te);
                        break;
                    }
                }
                XmlReader.newInstance().writeXml(list);
            }else{
                ///sysName不能为空
                Map<String, String> params = this.getParameterMap(request);
                if(StrUtil.isNull(params.get("serverIp"))) {
                    String serverIp = PortalPubFactory.getLocalIp();
                    params.put("serverIp", serverIp);
                }
                params.put("doCode", "delTaskTimer");
                params.put("taskKey", request.getParameter("key"));
                ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response, params);
                if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
                    rmsg = new ResultMsg("T", String.valueOf(entity.getEntity()));
                } else {
                    rmsg = new ResultMsg("F", entity.getMessage());
                }
            }
		}
		return rmsg;
	}

	//停止线程
	@RequestMapping(value = "stop.action")
	public ResultMsg stop(HttpServletRequest request, HttpServletResponse response) {
		String key = request.getParameter("key");
        if("file".equals(isFile)){
            log.info("[定时任务停用][本地文件内]->[key="+key+"]");
            if (StrUtil.isNull(key)) {//开启所有线程
                ScheduledExecutor.newInstance().stopTasks();
                log.info("[定时任务停用][全部停用]");
            } else {//开启指定线程
                ScheduledExecutor.newInstance().stopTaskByKey(key);
            }
        }else{
            String serverIp = PortalPubFactory.getLocalIp();
            String sysName = request.getParameter("sysName");
            log.info("[定时任务停用][远程数据库内]->[serverIp="+serverIp+"][sysName="+sysName+"][key="+key+"]");
            if (StrUtil.isNull(key)) {//开启所有线程
                ScheduledExecutor.newInstance().stopTasks(sysName,serverIp);
                log.info("[定时任务停用][全部停用]");
            } else {//开启指定线程
                ScheduledExecutor.newInstance().stopTaskByKey(sysName,key,serverIp);
            }
        }
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");
		return rmsg;
	}

    //开启线程
    @RequestMapping(value = "start.action")
    public ResultMsg start(HttpServletRequest request, HttpServletResponse response) {
        String key = request.getParameter("key");
        if("file".equals(isFile)){
            log.info("[定时任务启用][本地文件内]->[key="+key+"]");
            if (StrUtil.isNull(key)) {//开启所有线程
                ScheduledExecutor.newInstance().start();
                log.info("[定时任务启用][全部启用]");
            } else {//开启指定线程
                ScheduledExecutor.newInstance().start(key);
            }
        }else{
            String serverIp = PortalPubFactory.getLocalIp();
            String sysName = request.getParameter("sysName");
            log.info("[定时任务启用][远程数据库内]->[serverIp="+serverIp+"][sysName="+sysName+"][key="+key+"]");
            if (StrUtil.isNull(key)) {//开启所有线程
                ScheduledExecutor.newInstance().startBySysName(sysName,serverIp);
                log.info("[定时任务启用][全部启用]");
            } else {//开启指定线程
                ScheduledExecutor.newInstance().start(sysName,key,serverIp);
            }
        }
        ResultMsg rmsg = new ResultMsg("T", "操作成功！");
        return rmsg;
    }
}
